package com.ruoyi.file.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.file.model.vo.FileUploadInfo;
import com.ruoyi.file.service.ChunkUploadService;
import com.ruoyi.file.utils.MinioUtils;
import com.ruoyi.file.utils.RespEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/app/upload")
public class AppFileMinioChunkController {


    @Resource
    private MinioUtils minioUtils;
    @Resource
    private ChunkUploadService chunkUploadService;


    /**
     * 分片初始化
     *
     * @param fileUploadInfo 文件信息
     * @return ResponseResult<Object>
     */
    @PostMapping("/multipart/init")
    public R<Map<String, Object>> initMultiPartUpload(@RequestBody FileUploadInfo fileUploadInfo) {
        log.info("REST: 通过 <{}> 初始化上传任务", fileUploadInfo);
        return R.ok(chunkUploadService.initMultiPartUpload(fileUploadInfo));
    }

    /**
     * 判断是否是上传过的文件
     *
     * @param fileMD5 文件MD5
     * @return ResponseResult<Object>
     */
    @GetMapping("/multipart/secondPass")
    public R<Map<String, Object>> secondPass(String fileMD5) {
        return R.ok(chunkUploadService.secondPass(fileMD5));
    }

    /**
     * 完成上传
     *
     * @param fileUploadInfo 文件信息
     * @return ResponseResult<Object>
     */
    @PostMapping("/multipart/merge")
    @Log(title = "完成上传", businessType = BusinessType.INSERT, sysType = "app")
    public R<String> completeMultiPartUpload(@RequestBody FileUploadInfo fileUploadInfo) {
        log.info("REST: 通过 {} 合并上传任务", fileUploadInfo);
        //合并文件
        String url = chunkUploadService.mergeMultipartUpload(fileUploadInfo);
        //获取上传文件地址
        if (StringUtils.isNotBlank(url)) {
            return R.ok(url);
        }
        return R.fail();
    }

    /**
     * 校验文件是否存在
     *
     * @param md5 String
     * @return ResponseResult<Object>
     */
    @GetMapping("/multipart/check")
    public R<FileUploadInfo> checkFileUploadedByMd5(@RequestParam("md5") String md5) {
        log.info("REST: 通过查询 <{}> 文件是否存在、是否进行断点续传", md5);
        if (StringUtils.isEmpty(md5)) {
            log.error("查询文件是否存在、入参无效");
            return R.fail(RespEnum.ACCESS_PARAMETER_INVALID.getMessage());
        }
        return chunkUploadService.getByFileMD5(md5);
    }
}
